package com.xiaomo.gitee.datamanager.service.statistics.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaomo.gitee.datamanager.dto.statistics.StatisticsDataDTO;
import com.xiaomo.gitee.datamanager.mapper.CClassInfoMapper;
import com.xiaomo.gitee.datamanager.mapper.ClassInfoMapper;
import com.xiaomo.gitee.datamanager.mapper.ImagesMapper;
import com.xiaomo.gitee.datamanager.entity.CClassInfo;
import com.xiaomo.gitee.datamanager.entity.ClassInfo;
import com.xiaomo.gitee.datamanager.entity.Images;
import com.xiaomo.gitee.datamanager.service.statistics.StatisticsService;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@Service
@RequiredArgsConstructor
public class StatisticsServiceImpl implements StatisticsService {

    private final ImagesMapper imagesMapper;
    private final CClassInfoMapper childClassMapper;
    private final ClassInfoMapper parentClassMapper;

    @Override
    public List<StatisticsDataDTO> getParentClassStatistics() {
        List<StatisticsDataDTO> result = new ArrayList<>();
        List<ClassInfo> parentClasses = parentClassMapper.selectAll();
        for (ClassInfo classInfo : parentClasses) {

            StatisticsDataDTO dto = new StatisticsDataDTO();

            dto.setName(classInfo.getName());
            dto.setId(classInfo.getId());

            AtomicLong count = new AtomicLong();
            List<CClassInfo> child = childClassMapper.selectByPClassId(classInfo.getId());
            child.forEach((child2) -> {
                QueryWrapper<Images> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("classification",child2.getId());
                count.addAndGet(imagesMapper.selectCount(queryWrapper));
            });
            dto.setAmount(count.get());

            result.add(dto);
        }
        return result;
    }

    @Override
    public List<StatisticsDataDTO> getChildClassStatistics(Long pClassId) {
        List<CClassInfo> childClassList = childClassMapper.selectByPClassId(pClassId);
        List<StatisticsDataDTO> result = new ArrayList<>();
        for (CClassInfo child : childClassList) {
            StatisticsDataDTO dto = new StatisticsDataDTO();

            dto.setName(child.getName());
            //dto.setId(child.getId());

            QueryWrapper<Images> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("classification",child.getId());
            dto.setAmount(imagesMapper.selectCount(queryWrapper));

            result.add(dto);
        }
        return result;
    }

    @Override
    public Long getImagesAmount(){
        return imagesMapper.selectCount(new QueryWrapper<>());
    }
}
